import json
import os.path
import queue
import threading
import time
import datetime
from pathlib import Path

#-----------------------------
# install modbus libs
# pip3 install -i https://mirrors.tuna.tsinghua.edu.cn/pypi/web/simple  pymodbus==2.5.3  --低版本
#-----------------------------
from pymodbus.client.sync import ModbusSerialClient as ModbusClient
import serial, serial.tools.list_ports

print('check modbus rtu bus')

class TPyUtils:
    def __init__(self):
        pass
    @staticmethod
    def connectModbusRtu(comPort="COM1" , comBaudrate = 9600 , comStopBit = 1 , comParity='E' , comDataBit= 8 ):
        res = None
        try:
            client = ModbusClient(
                method="rtu" ,
                port= comPort , baudrate=comBaudrate , stopbits=comStopBit, parity= comParity, bytesize=comDataBit ,
                strict= False,
                timeout= 2
                )
            client.connect()
            res = client
        except Exception as er:
            print(er)
        return  res

_comPort="/dev/ttyS0"
_comBaudrate = 9600
_comStopBit = 1
_comParity='N'
_comDataBit= 8


client = ModbusClient(
                method="rtu" ,
                port= '/dev/ttyS1' , baudrate=9600 , stopbits=1, parity= 'N', bytesize=8 ,
                strict= False,
                timeout= 2
                )
connFlag = client.connect()
print('wait...')
time.sleep(2)
print(client , connFlag)

unitId = 13
regStart = 30073
regLen = 2

result = client.read_holding_registers(regStart, regLen, unit=unitId)
isError = result.isError()
if isError:
    print('collect faild', regStart, result)
else:
    regs = list(result.registers)
    print(regs)


